<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
     <el-card class="box-card">
      <!-- 搜索 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入内容"
            class="input-with-select"
            v-model="queryInfo.query"
            clearable
            @clear="getUserList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 表格 -->
      <el-table :data="userlist" style="width: 100%" stripe border>
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="userStateChanged(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" icon="el-icon-edit" @click='showEditDialog(scope.row.id)'></el-button>
            <el-button size="mini" type="danger" icon="el-icon-delete" @click="showDeleteDialog(scope.row.id)"></el-button>
            <el-tooltip effect="dark" class="item" content="分配角色" placement="top" :enterable="false">
              <el-button size="mini" type="warning" icon="el-icon-setting" @click="setRole(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
       <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="queryInfo.pagenum"
      :page-sizes="[1, 2, 5, 10]"
      :page-size="queryInfo.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
    </el-card>
    <!-- 添加用户的对话框 -->
    <el-dialog
  title="添加用户"
  width="50%"
  :visible.sync="addDialogVisible"
  @close="addFormClose">
  <el-form label-width="70px" :model="addForm" :rules="addFormRules" ref="addFormRef">
    <el-form-item label="用户名" prop="username">
      <el-input v-model="addForm.username"></el-input>
    </el-form-item>
    <el-form-item label="密码" prop="password">
      <el-input v-model="addForm.password"></el-input>
    </el-form-item>
    <el-form-item label="邮箱" prop="email">
      <el-input v-model="addForm.email"></el-input>
    </el-form-item>
    <el-form-item label="手机" prop="mobile">
      <el-input v-model="addForm.mobile"></el-input>
    </el-form-item>
  </el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="addDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addUser()">确 定</el-button>
  </span>
    </el-dialog>
    <!-- 编辑用户的对话框 -->
    <el-dialog
  title="编辑用户"
  :visible.sync="editDialogVisible"
  width="50%"
  @close="editDialogClose">
  <el-form label-width="70px" :model="editForm" :rules="editFormRules" ref="editFormRef">
    <el-form-item label="用户名">
      <el-input v-model="editForm.username" disabled></el-input>
    </el-form-item>
    <el-form-item label="邮箱" prop="email">
      <el-input v-model="editForm.email"></el-input>
    </el-form-item>
    <el-form-item label="手机" prop="mobile">
      <el-input v-model="editForm.mobile"></el-input>
    </el-form-item>
  </el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="editDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="editUser()">确 定</el-button>
  </span>
</el-dialog>
    <!-- 分配角色的对话框 -->
    <el-dialog
  title="分配角色"
  :visible.sync="setRoleDialogVisible"
  width="50%"
  @close="setRoleDialogClosed">
  <div>
    <p>当前的用户：{{userInfo.username}}</p>
    <p>当前的角色：{{userInfo.role_name}}</p>
    <p>分配新角色：
      <el-select v-model="selectedRoleId" placeholder="请选择">
    <el-option
      v-for="item in rolesList"
      :key="item.id"
      :label="item.roleName"
      :value="item.id">
    </el-option>
  </el-select>
    </p>
  </div>
  <span slot="footer" class="dialog-footer">
    <el-button @click="setRoleDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
  </span>
</el-dialog>

  </div>
</template>

<script>
import { changeUserState, addUsers, findUserInfo, editUserInfo, delUser, getRolesLists, assignRoles } from './service'
export default {
  data() {
    var checkEmail = (rule, value, cb) => {
      const regEmail = /^([0-9a-zA-Z_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (regEmail.test(value)) {
        return cb()
      }
      cb(new Error('请输入合法的邮箱'))
    }
    var checkMobile = (rule, value, cb) => {
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (regMobile.test(value)) {
        return cb()
      }
      cb(new Error('请输入合法的手机号'))
    }
    return {
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      total: 0,
      userlist: [],
      addDialogVisible: false,
      // 添加用户表单数据
      addForm: {
        username: '111',
        password: '123456',
        email: '1202@qq.com',
        mobile: '13566669999'
      },
      // 表单验证规则
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '用户名的长度在3~10个字符之间', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '用户名的长度在6~15个字符之间', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      editDialogVisible: false,
      editForm: {},
      editFormRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      deleteDialogVisible: false,
      // 分配角色对话框显示与隐藏
      setRoleDialogVisible: false,
      // 需要被分配角色的用户信息
      userInfo: {},
      // 所有角色数据列表
      rolesList: [],
      // 已选中的角色id值
      selectedRoleId: ''
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    async getUserList () {
      const { data: res } = await this.$http.get('users', {
        params: this.queryInfo
      })
      if (res.meta.status !== 200) return this.$message.error('获取用户列表失败')
      this.userlist = res.data.users
      console.log(this.userlist)
      this.total = res.data.total
      this.$message.success('获取用户列表成功')
    },
    // 监听 pagesize 改变的事件
    handleSizeChange(newSize) {
      // console.log(newSize)
      this.queryInfo.pagesize = newSize
      this.getUserList()
    },
    // 监听 页码值 改变的事件
    handleCurrentChange(newPage) {
      console.log(newPage)
      this.queryInfo.pagenum = newPage
      this.getUserList()
    },
    // 监听switch 状态改变
    async userStateChanged(userInfo) {
      changeUserState(userInfo.id, userInfo.mg_state).then(res => {
        if (res.data.meta.status !== 200) {
          userInfo.mg_state = !userInfo.mg_state
          return this.$message.error('更新用户状态失败')
        }
        this.$message.success('更新用户状态成功')
      })
    },
    // 添加用户
    addUser() {
      this.$refs.addFormRef.validate(valid => {
        if (!valid) return
        addUsers(this.addForm).then(res => {
          if (res.data.meta.status !== 201) {
            return this.$message.error('添加用户失败')
          }
          this.$message.success('添加用户成功')
          this.addDialogVisible = !this.addDialogVisible
          this.getUserList()
        })
      })
    },
    // 监听添加用户对话框的关闭
    addFormClose() {
      this.$refs.addFormRef.resetFields()
    },
    // 监听编辑用户对话框的打开关闭
    showEditDialog(id) {
      findUserInfo(id).then(res => {
        if (res.data.meta.status !== 200) {
          return this.$message.error('获取用户信息失败')
        }
        this.$message.success('获取用户信息成功')
        this.editForm = res.data.data
      })
      this.editDialogVisible = true
    },
    // 编辑用户信息 提交
    editUser() {
      this.$refs.editFormRef.validate(valid => {
        if (valid) return
        const param = {
          email: this.editForm.email,
          mobile: this.editForm.mobile
        }
        editUserInfo(this.editForm.id, param).then(res => {
          if (res.data.meta.status !== 200) {
            return this.$message.error('修改用户信息失败')
          }
          this.editDialogVisible = false
          this.getUserList()
          this.$message.success('修改用户信息成功')
        })
      })
    },
    // 监听编辑用户对话框的关闭
    editDialogClose() {
      this.$refs.editFormRef.resetFields()
    },
    // 打开删除弹框
    async showDeleteDialog(id) {
      const confirm = await this.$confirm('确认删除用户吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirm !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      delUser(id).then(res => {
        console.log(res.data)
        if (res.data.meta.status !== 200) {
          return this.$message.error('删除用户失败')
        }
        this.getUserList()
        this.$message.success('删除用户成功')
      })
    },
    // 分配角色
    setRole(userInfo) {
      this.userInfo = userInfo
      // 打开对话框前 发送请求 获取角色列表
      getRolesLists().then(res => {
        if (res.data.meta.status !== 200) {
          return this.$message.error('获取角色权限列表失败')
        }
        this.$message.success('获取角色权限列表成功')
        this.rolesList = res.data.data
      })
      this.setRoleDialogVisible = true
    },
    saveRoleInfo() {
      if (!this.selectedRoleId) {
        return this.$message.error('请选择要分配的角色')
      }
      assignRoles(this.userInfo.id, this.selectedRoleId).then(res => {
        if (res.data.meta.status !== 200) {
          return this.$message.error('设置角色失败')
        }
        this.$message.success('设置角色成功')
        this.getUserList()
        this.setRoleDialogVisible = false
      })
    },
    // 分配角色对话框的关闭
    setRoleDialogClosed() {
      this.selectedRoleId = ''
      this.userInfo = {}
    }
  }
}
</script>

<style lang="less" scoped>
</style>
